// Package crons
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2023 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
package crons

import (
	"context"
	"encoding/json"
	"fmt"
	"hotgo/internal/library/cron"
	"hotgo/internal/model/input/sysin"
	"hotgo/internal/service"
	"hotgo/utility/client"
	"io"
	"strconv"
	"time"
)

func init() {
	cron.Register(StockEmotion)
}

// StockEmotion 测试任务（无参数）
var StockEmotion = &cStockEmotion{name: "stock_emotion"}
var StockEmotionUrls = map[string]string{
	"开盘啦": "https://apphq.longhuvip.com/w1/api/index.php?a=ChangeStatistics&apiv=w33&c=HomeDingPan&PhoneOSNew=1&UserID=497432&DeviceID=ffffffff-e91e-5efd-ffff-ffffa460846b&VerSion=5.11.0.6&Token=4761ad40037d3c58725b7966dbcbfdd2&",
}

type StockKPLEmotionResp struct {
	ErrCode string             `json:"errcode"`
	Tip     string             `json:"tip"`
	Info    []StockEmotionItem `json:"info"`
}

type StockEmotionItem struct {
	Ztjs   string `json:"ztjs"`
	Strong string `json:"strong"`
	Lbgd   string `json:"lbgd"`
	Day    string `json:"Day"`
	DfNum  string `json:"df_num"`
}

type cStockEmotion struct {
	name string
}

func (c *cStockEmotion) GetName() string {
	return c.name
}

// Execute 执行任务
func (c *cStockEmotion) Execute(ctx context.Context, parser *cron.Parser) (err error) {
	for source, StockEmotionUrl := range StockEmotionUrls {
		time.Sleep(1 * time.Second)
		httpClient := client.GetClient()
		response, err := httpClient.Get(ctx, fmt.Sprintf("%s", StockEmotionUrl))
		if err != nil {
			parser.Logger.Warning(ctx, "cron CloseOrder Execute http.Get err:%+v", err)
			continue
		}
		defer response.Body.Close()
		body, err := io.ReadAll(response.Body)
		if err != nil {
			parser.Logger.Warning(ctx, "cron CloseOrder Execute io.ReadAll err:%+v", err)
			continue
		}
		switch source {
		case "开盘啦":
			var resp StockKPLEmotionResp
			err = json.Unmarshal(body, &resp)
			if err != nil {
				parser.Logger.Warning(ctx, "cron CloseOrder Execute json.Unmarshal err:%+v", err)
				continue
			}
			if resp.ErrCode == "0" {
				for _, emResp := range resp.Info {
					var editInp = &sysin.StockEmotionEditInp{}
					Ztjs, _ := strconv.Atoi(emResp.Ztjs)
					Strong, _ := strconv.Atoi(emResp.Strong)
					Lbgd, _ := strconv.Atoi(emResp.Lbgd)
					DfNum, _ := strconv.Atoi(emResp.DfNum)
					editInp.Ztjs = Ztjs
					editInp.Strong = Strong
					editInp.Date = emResp.Day
					editInp.Lbgd = Lbgd
					editInp.DmNum = DfNum
					err := service.SysStockEmotion().Edit(ctx, editInp)
					if err != nil {
						parser.Logger.Warning(ctx, "cron CloseOrder Execute service.SysStockZhASpotEm().Edit err:%+v", err)
						continue
					}
				}
			}

		}
	}

	return
}
